package com.tanglon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanglon.domain.ResponseResult;
import com.tanglon.domain.dto.*;
import com.tanglon.domain.entity.Role;
import com.tanglon.domain.entity.User;
import com.tanglon.domain.entity.UserRole;
import com.tanglon.domain.vo.*;
import com.tanglon.enums.AppHttpCodeEnum;
import com.tanglon.exception.SystemException;
import com.tanglon.mapper.UserMapper;
import com.tanglon.service.RoleService;
import com.tanglon.service.UserRoleService;
import com.tanglon.service.UserService;
import com.tanglon.utils.BeanCopyUtils;
import com.tanglon.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2025-08-09 16:55:47
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    @Override
    public ResponseResult userInfo() {
        //获取当前用户Id
        Long userId = SecurityUtils.getUserId();
        //根据用户id获取信息
        User user = getById(userId);
        //封装
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        return ResponseResult.okResult(userInfoVo);
    }

    @Override
    public ResponseResult updateUserInfo(UserInfoDTO userInfoDTO) {
        updateById(BeanCopyUtils.copyBean(userInfoDTO, User.class));
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult register(RegisterDTO registerDTO) {
        //对前端传来的注册信息进行判断
        if(!StringUtils.hasText(registerDTO.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if (!StringUtils.hasText(registerDTO.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if(!StringUtils.hasText(registerDTO.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        if(!StringUtils.hasText(registerDTO.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        //对用户名、昵称和邮箱进行判断是否存在数据库中
        if(userNameExist(registerDTO.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if(nickNameExist(registerDTO.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        if(emailExist(registerDTO.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        //对密码进行加密
        String encodePassword = passwordEncoder.encode(registerDTO.getPassword());
        //数据封装
        User user = BeanCopyUtils.copyBean(registerDTO, User.class);
        user.setPassword(encodePassword);
        save(user);
        return ResponseResult.okResult();
    }

    private boolean emailExist(String email) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, email);
        return count(queryWrapper)>0;
    }

    private boolean userNameExist(String userName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, userName);
        return count(queryWrapper)>0;
    }

    private boolean nickNameExist(String nickName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getNickName, nickName);
        return count(queryWrapper)>0;
    }

    @Override
    public ResponseResult userList(Integer pageNum, Integer pageSize, String userName, String phonenumber, String status) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Objects.nonNull(userName),User::getUserName, userName);
        queryWrapper.eq(Objects.nonNull(phonenumber),User::getPhonenumber,phonenumber);
        queryWrapper.eq(Objects.nonNull(status),User::getStatus,status);

        Page<User> page = new Page<>(pageNum, pageSize);
        page(page, queryWrapper);
        List<UserVo> userVos=BeanCopyUtils.copyBeanList(page.getRecords(), UserVo.class);
        PageVo pageVo=new PageVo(userVos,page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    @Transactional
    public ResponseResult addUser(AddUserDTO addUserDTO) {
        //        1.用户名不能为空，否则提示：必需填写用户名
        if (Objects.isNull(addUserDTO.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        //    	  2.用户名必须之前未存在，否则提示：用户名已存在
//        if (!userMapper.selectUserNameBoolean(userVo2.getUserName())){
//            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
//        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,addUserDTO.getUserName());
        if (getOne(queryWrapper) != null){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }

//        3.手机号必须之前未存在，否则提示：手机号已存在
//        if (!userMapper.selectPhoneBoolean(userVo2.getPhonenumber())){
//            throw new SystemException(AppHttpCodeEnum.PHONENUMBER_EXIST)
//        }
        LambdaQueryWrapper<User> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(User::getPhonenumber,addUserDTO.getPhonenumber());
        if (getOne(queryWrapper1) != null){
            throw new SystemException(AppHttpCodeEnum.PHONENUMBER_EXIST);
        }

//    	   4.邮箱必须之前未存在，否则提示：邮箱已存在
//        if (!userMapper.selectEmailBoolean(userVo2.getEmail())){
//            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
//        }
        LambdaQueryWrapper<User> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(User::getEmail,addUserDTO.getEmail());
        if (getOne(queryWrapper2) != null){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        //1.保存到 user表
        User user = BeanCopyUtils.copyBean(addUserDTO, User.class);
        //对密码进行加密
        String encodePassword = passwordEncoder.encode(user.getPassword());//对明文密码 进行加密，得到密文
        user.setPassword(encodePassword); //将password加密后的密文,存到user中
        save(user);

        //2.保存到user_role表
        Long userId = user.getId();
        List<UserRole> userRoles = addUserDTO.getRoleIds().stream()
                .map(roleId -> new UserRole(userId, Long.parseLong(roleId)))
                .collect(Collectors.toList());

        userRoleService.saveBatch(userRoles);

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getUserDetail(Long id) {
        UserAndRoleVo userAndRoleVo=new UserAndRoleVo();
        //根据id查找用户关联角色
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,id);
        List<UserRole> userRoles = userRoleService.list(queryWrapper);
        List<String> roleIds = userRoles.stream()
                .map(userRole -> userRole.getRoleId().toString())
                .collect(Collectors.toList());
        userAndRoleVo.setRoleIds(roleIds);
        //获取正常的角色身份
        LambdaQueryWrapper<Role> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Role::getStatus,0);
        List<Role> roleList=roleService.list(queryWrapper1);
        userAndRoleVo.setRoles(roleList);
        //查询用户信息

        User user=getById(id);
        UserVo2 userDTO = BeanCopyUtils.copyBean(user, UserVo2.class);
        userAndRoleVo.setUser(userDTO);
        return ResponseResult.okResult(userAndRoleVo);
    }

    @Override
    @Transactional
    public ResponseResult updateUser(UpdateUserDTO updateUserDTO) {
        User user = BeanCopyUtils.copyBean(updateUserDTO, User.class);
        updateById(user);
        //先删再加
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,user.getId());
        userRoleService.remove(queryWrapper);
        List<UserRole> userRoles = updateUserDTO.getRoleIds().stream()
                .map(roleId -> new UserRole(user.getId(), Long.parseLong(roleId)))
                .collect(Collectors.toList());
        userRoleService.saveBatch(userRoles);
        return ResponseResult.okResult();
    }
}

